import type Stomp from "stompjs";
import { useSocketPinia } from "@/pinia/socket";
import { useDynamicPinia } from "@/pinia/dynamic";
import { storeToRefs } from "pinia";

export default (token: string) => {
  const socketStore = useSocketPinia();
  const { dynamicDatas, mySelfDynamicDatas } = storeToRefs(useDynamicPinia());
  // 通知有权限的好友自己已经删掉了某条动态（订阅接口）
  socketStore.SOCKET_SUBSRCIBE({
    url: `/dynamic/${token}/deleteDynamic`,
    callback: (res: Stomp.Message) => {
      const body: {
        dynamicId: string;
      } = JSON.parse(res.body);
      const data = dynamicDatas.value.value;
      data.size && data.delete(body.dynamicId);
    },
  });

  // 通知发表了该动态的好友及能看到该条动态的好友我已经对该条动态点赞或者取消了点赞(前提是被通知方一定是我的好友)
  socketStore.SOCKET_SUBSRCIBE({
    url: `/dynamic/${token}/thumbDynamic`,
    callback: (res: Stomp.Message) => {
      const body: {
        dynamicId: string;
        userId: string;
        remark: string;
      } = JSON.parse(res.body);
      const data = dynamicDatas.value.value.get(body.dynamicId);
      const myData = mySelfDynamicDatas.value.value.get(body.dynamicId);
      if (data && !data.thumbs.delete(body.userId))
        data.thumbs.set(body.userId, { remark: body.remark })
      if (myData && !myData.thumbs.delete(body.userId))
        myData.thumbs.set(body.userId, { remark: body.remark })
    },
  });

  // 通知发表了该动态的好友及能看到该条动态的好友我已经对该条动态评论了或者回复了某条评论
  socketStore.SOCKET_SUBSRCIBE({
    url: `/dynamic/${token}/commentDynamic`,
    callback: (res: Stomp.Message) => {
      const body: {
        dynamicId: string;
        commentId: string;
        info: {
          commentContent: string;
        } & DynamicCommenter;
      } = JSON.parse(res.body);
      const data = dynamicDatas.value.value.get(body.dynamicId);
      const myData = mySelfDynamicDatas.value.value.get(body.dynamicId);
      if (data) data.comments.set(body.commentId, body.info);
      if (myData) myData.comments.set(body.commentId, body.info);
    },
  });

  // 通知发表了该动态的好友及能看到该条动态的好友我已经删除了某条评论
  socketStore.SOCKET_SUBSRCIBE({
    url: `/dynamic/${token}/commentDynamicDelete`,
    callback: (res: Stomp.Message) => {
      const body: {
        dynamicId: string;
        commentId: string;
      } = JSON.parse(res.body);
      const data = dynamicDatas.value.value.get(body.dynamicId);
      const myData = mySelfDynamicDatas.value.value.get(body.dynamicId);
      if (data) data.comments.delete(body.commentId);
      if (myData) myData.comments.delete(body.commentId);
    },
  });
}